package cn.fancylab.template.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import cn.fancylab.model.bs.DeviceCabinetBox;
import cn.fancylab.model.bs.DeviceController;
import cn.fancylab.model.bs.DeviceGateway;
import cn.fancylab.service.impl.BaseServiceImpl;
import cn.fancylab.template.service.DeviceControllerService;

@Service("deviceControllerService")
public class DeviceControllerServiceImpl extends BaseServiceImpl implements DeviceControllerService {

	@Override
	public String saveDeviceController(DeviceController deviceController) {
		List list = baseDao.findByHql("from DeviceController where identified_no = ?0",
				deviceController.getIdentified_no());
		if (list != null && list.size() > 0) {
			if (list.size() == 1) {
				DeviceController dc = (DeviceController) list.get(0);
				BeanUtils.copyProperties(deviceController, dc, new String[] { "deviceGetwayList", "uuid" });
				baseDao.saveObject(dc);
			} else {
				return "中控信息重复";
			}
		} else {
			deviceController.setUuid(UUID.randomUUID().toString());
			baseDao.saveObject(deviceController);
		}

		for (DeviceGateway deviceGateway : deviceController.getDeviceGatewayList()) {
			list = baseDao.findByHql("from DeviceGateway where identified_no = ?0", deviceGateway.getIdentified_no());
			if (list != null && list.size() > 0) {
				if (list.size() == 1) {
					DeviceGateway dg = (DeviceGateway) list.get(0);
					BeanUtils.copyProperties(deviceGateway, dg, new String[] { "devicePartitionplateList", "uuid" });
					baseDao.saveObject(dg);
				} else {
					throw new NullPointerException();
				}
			} else {
				deviceGateway.setBs_d_controller_uuid(deviceController.getUuid());
				deviceGateway.setUuid(UUID.randomUUID().toString());
				baseDao.saveObject(deviceGateway);
			}

			for (DeviceCabinetBox deviceCabinetBox : deviceGateway.getDeviceCabinetBoxList()) {
				list = baseDao.findByHql("from DeviceCabinetBox where alias_name = ?0",
						deviceCabinetBox.getAlias_name());
				if (list != null && list.size() > 0) {
					if (list.size() == 1) {
						DeviceCabinetBox dc = (DeviceCabinetBox) list.get(0);
						BeanUtils.copyProperties(deviceCabinetBox, dc, new String[] { "uuid" });
						baseDao.saveObject(dc);
					} else {
						throw new NullPointerException();
					}
				} else {
					deviceCabinetBox.setBs_d_gateway_uuid(deviceGateway.getUuid());
					deviceCabinetBox.setUuid(UUID.randomUUID().toString());
					baseDao.saveObject(deviceCabinetBox);
				}
			}
		}

		return null;
	}
}
